const http = require('http');
const fs = require('fs');
// 引入url模块，解析请求的路径
const url = require('url');
const querystring = require('querystring');

let sever = http.createServer();

sever.on('request', (req, res) => {
  let { pathname, query } = url.parse(req.url, true);
  switch (pathname) {
    case '/':
      console.log(666);
      res.setHeader("Content-Type", "text/html;charset=utf8");
      fs.readFile('./form.html', 'utf8', (err,data) => {
        if(err){
          throw err
        }else{
          res.write(data);
          res.end();
        }
      })
      break;
    case '/form.css':
      fs.readFile('./form.css', (err,data) => {
        if(err){
          throw err
        }else{
          res.end(data);
        }
      })
      break;
    case '/login':
      res.setHeader("Content-Type", "text/html;charset=utf8");
      res.write(`
        欢迎您, ${query.username},
        您的密码是：${query.pwd},
        本次登录时间： ${new Date()}
      `);
      res.end();
      break;
    case '/login2':
      res.setHeader("Content-Type", "text/html;charset=utf8");
      // 判断请求的方式为post
      if(req.method.toLowerCase() === 'post') {
        let reqBody = '';
        req.on('data', data => {
          // console.log(decodeURIComponent(data));
          reqBody += data
        })
        req.on('end', () => {
          let dataObj = querystring.parse(reqBody.toString());
          res.write(`
            欢迎您, ${dataObj.username},
            您的密码是：${dataObj.pwd},
            本次登录时间： ${new Date()}
          `);
          res.end();
        })
        break;
      }
    default:
      break;
  }
})

sever.listen(8080, '127.0.0.1', () => {
  console.log('OK')
})